console.log('Popup test script loaded');

function log(message, type = 'info') {
    const logs = document.getElementById('logs');
    const div = document.createElement('div');
    div.className = type;
    div.textContent = new Date().toLocaleTimeString() + ': ' + message;
    logs.appendChild(div);
    logs.scrollTop = logs.scrollHeight;
    console.log(message);
}

function clearLogs() {
    document.getElementById('logs').innerHTML = '<div class="info">日志已清除</div>';
}

// 测试Service Worker连接
async function testConnection() {
    log('正在测试Service Worker连接...', 'info');
    try {
        const response = await chrome.runtime.sendMessage({type: 'test'});
        log('Service Worker响应: ' + JSON.stringify(response), 'success');
    } catch (error) {
        log('Service Worker连接失败: ' + error.message, 'error');
    }
}

// 测试API连接
async function testAPI() {
    log('正在测试API连接...', 'info');
    try {
        const response = await chrome.runtime.sendMessage({type: 'indexData'});
        log('API响应: ' + JSON.stringify(response).substring(0, 200) + '...', 'success');
    } catch (error) {
        log('API连接失败: ' + error.message, 'error');
    }
}

// 测试存储功能
async function testStorage() {
    log('正在测试存储功能...', 'info');
    try {
        // 写入测试数据
        await chrome.storage.local.set({test: 'Hello World'});
        log('存储写入成功', 'success');
        
        // 读取测试数据
        const result = await chrome.storage.local.get('test');
        log('存储读取成功: ' + result.test, 'success');
        
        // 删除测试数据
        await chrome.storage.local.remove('test');
        log('存储删除成功', 'success');
    } catch (error) {
        log('存储测试失败: ' + error.message, 'error');
    }
}

// 页面加载完成
document.addEventListener('DOMContentLoaded', function() {
    log('测试页面加载完成', 'success');
    log('Chrome版本: ' + navigator.userAgent.match(/Chrome\/(\d+)/)[1], 'info');
    
    // 绑定事件
    document.getElementById('testConnection').addEventListener('click', testConnection);
    document.getElementById('testAPI').addEventListener('click', testAPI);
    document.getElementById('testStorage').addEventListener('click', testStorage);
    document.getElementById('clearLogs').addEventListener('click', clearLogs);
});

// 错误捕获
window.addEventListener('error', function(e) {
    log('页面错误: ' + e.message, 'error');
});
